package com.mall.order.services;

import com.mall.commons.tool.exception.ValidateException;
import com.mall.order.OrderCoreService;
import com.mall.order.biz.TransOutboundInvoker;
import com.mall.order.biz.context.AbsTransHandlerContext;
import com.mall.order.biz.factory.OrderProcessPipelineFactory;
import com.mall.order.constant.OrderRetCode;
import com.mall.order.constants.OrderConstants;
import com.mall.order.dal.entitys.Order;
import com.mall.order.dal.entitys.OrderItem;
import com.mall.order.dal.entitys.Stock;
import com.mall.order.dal.persistence.OrderItemMapper;
import com.mall.order.dal.persistence.OrderMapper;
import com.mall.order.dal.persistence.OrderShippingMapper;
import com.mall.order.dal.persistence.StockMapper;
import com.mall.order.dto.*;
import com.mall.order.utils.ExceptionProcessorUtils;
import com.mall.user.constants.SysRetCodeConstants;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 *  ciggar
 * create-date: 2019/7/30-上午10:05
 */
@Transactional(rollbackFor = Exception.class)
@Slf4j
@Component
@Service(cluster = "failfast")
public class OrderCoreServiceImpl implements OrderCoreService {

	@Autowired
	OrderMapper orderMapper;

	@Autowired
	OrderItemMapper orderItemMapper;

	@Autowired
	OrderShippingMapper orderShippingMapper;

	@Autowired
    OrderProcessPipelineFactory orderProcessPipelineFactory;

	@Autowired
	StockMapper stockMapper;


	/**
	 * 创建订单的处理流程
	 *
	 * @param request
	 * @return
	 */
	@Override
	public CreateOrderResponse createOrder(CreateOrderRequest request) {
		CreateOrderResponse response = new CreateOrderResponse();
		try {
			//创建pipeline对象
			TransOutboundInvoker invoker = orderProcessPipelineFactory.build(request);

			//启动pipeline
			invoker.start(); //启动流程（pipeline来处理）

			//获取处理结果
			AbsTransHandlerContext context = invoker.getContext();

			//把处理结果转换为response
			response = (CreateOrderResponse) context.getConvert().convertCtx2Respond(context);
		} catch (Exception e) {
			log.error("OrderCoreServiceImpl.createOrder Occur Exception :" + e);
			ExceptionProcessorUtils.wrapperHandlerException(response, e);
		}
		return response;
	}

	/**
	 * 取消订单(把订单状态从0修改为7 + 还原锁定库存)
	 * @param request
	 * @return
	 */
	@Override
	public CancelOrderResponse cancelOrder(CancelOrderRequest request) {

		CancelOrderResponse response = new CancelOrderResponse();

		try {
			//参数校验
			request.requestCheck();

			//业务逻辑 sql + mapStruct
			//改变商品状态
			Integer affectedRows = orderMapper.cancelOrder(request.getOrderId());

			//锁定库存返还
			Example example = new Example(OrderItem.class);
			Example.Criteria criteria = example.createCriteria();
			criteria.andEqualTo("orderId",request.getOrderId());
			List<OrderItem> orderItems = orderItemMapper.selectByExample(example);

			for (OrderItem orderItem : orderItems) {
				Integer num = orderItem.getNum();
				Stock unModifyStock = stockMapper.selectById(orderItem.getItemId());
				Stock stock = new Stock();
				stock.setItemId(orderItem.getItemId());
				stock.setLockCount(unModifyStock.getLockCount() - num);
				stock.setStockCount(unModifyStock.getStockCount() + num);
				int affectedRows2 = stockMapper.updateById(stock);
			}

			//返回值
			response.setCode(OrderRetCode.SUCCESS.getCode());
			response.setMsg(OrderRetCode.SUCCESS.getMessage());

		}catch (ValidateException e){
			response.setCode(e.getErrorCode());
			response.setMsg(e.getMessage());
		}catch (Exception e){
			e.printStackTrace();
			response.setCode(OrderRetCode.DB_EXCEPTION.getCode());
			response.setMsg(OrderRetCode.DB_EXCEPTION.getMessage());
		}
		return response;
	}

	/**
	 * 删除订单的业务逻辑(删order、order_item、order_shipping表)
	 * @param request
	 * @return
	 */
	@Override
	public DeleteOrderResponse deleteOrder(DeleteOrderRequest request) {

		DeleteOrderResponse response = new DeleteOrderResponse();

		try {
			//参数校验
			request.requestCheck();

			//业务逻辑
			int affectedRows1 = orderMapper.deleteByPrimaryKey(request.getOrderId());
			int affectedRows2 = orderItemMapper.deleteByOrderId(request.getOrderId());
			int affectedRows3 = orderShippingMapper.deleteByPrimaryKey(request.getOrderId());

			//返回值
			response.setCode(OrderRetCode.SUCCESS.getCode());
			response.setMsg(OrderRetCode.SUCCESS.getMessage());

		}catch (ValidateException e){
			response.setCode(e.getErrorCode());
			response.setMsg(e.getMessage());
		}catch (Exception e){
			e.printStackTrace();
			response.setCode(OrderRetCode.DB_EXCEPTION.getCode());
			response.setMsg(OrderRetCode.DB_EXCEPTION.getMessage());
		}
		return response;
	}

}
